package com.sinosoft.taxbenefit.manage.main.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.sinosoft.taxbenefit.manage.base.entity.BaseEntity.DELETED;
import com.sinosoft.taxbenefit.manage.base.entity.BaseEntity.STATE;
import com.sinosoft.taxbenefit.manage.base.util.HtmlUtil;
import com.sinosoft.taxbenefit.manage.base.util.MethodUtil;
import com.sinosoft.taxbenefit.manage.base.util.SessionUtils;
import com.sinosoft.taxbenefit.manage.base.web.BaseAction;
import com.sinosoft.taxbenefit.manage.jeecg.biz.service.impl.SysRoleService;
import com.sinosoft.taxbenefit.manage.jeecg.biz.service.impl.SysUserService;
import com.sinosoft.taxbenefit.manage.jeecg.entity.SysRole;
import com.sinosoft.taxbenefit.manage.jeecg.entity.SysRoleRel;
import com.sinosoft.taxbenefit.manage.jeecg.entity.SysUser;
import com.sinosoft.taxbenefit.manage.jeecg.exception.ServiceException;
import com.sinosoft.taxbenefit.manage.jeecg.page.SysUserModel;
import com.sinosoft.taxbenefit.manage.main.web.util.MainViewConstant;

/**
 * 系统用户管理
 * @author zhangke
 *
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseAction {

	// Servrice start
	@Autowired
	private SysUserService<SysUser> sysUserService;

	// Servrice start
	@Autowired
	private SysRoleService<SysRole> sysRoleService;

	/**
	 * ilook 首页
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 */
	@RequestMapping("/list.do")
	public ModelAndView list(SysUserModel model, HttpServletRequest request)
			throws Exception {
		Map<String, Object> context = getRootMap();
		List<SysUser> dataList = sysUserService.queryByList(model);
		// 设置页面数据
		context.put("dataList", dataList);
		return forword(MainViewConstant.MAIN_USER_VIEW, context);
	}

	/**
	 * json 列表页面
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/dataList.do")
	public void dataList(SysUserModel model, HttpServletResponse response)
			throws Exception {
		List<SysUser> dataList = sysUserService.queryByList(model);
		for (SysUser user : dataList) {
			List<SysRole> list = sysRoleService.queryByUserid(user.getSid());
			user.setRoleStr(rolesToStr(list));
		}
		// 设置页面数据
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("total", model.getPager().getRowCount());
		jsonMap.put("rows", dataList);
		HtmlUtil.writerJson(response, jsonMap);
	}

	/**
	 * 角色列表转成字符串
	 * 
	 * @param list
	 * @return
	 */
	private String rolesToStr(List<SysRole> list) {
		if (list == null || list.isEmpty()) {
			return null;
		}
		StringBuffer str = new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			SysRole role = list.get(i);
			str.append(role.getRoleName());
			if ((i + 1) < list.size()) {
				str.append(",");
			}
		}
		return str.toString();
	}

	/**
	 * 添加或修改数据
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save.do")
	public void save(SysUser bean, HttpServletResponse response)
			throws Exception {
		int count = sysUserService.getUserCountByEmail(bean.getEmail());
		if (bean.getSid() == null) {
			if (count > 0) {
				throw new ServiceException("用户已存在.");
			}
			bean.setDeleted(DELETED.NO.key);
			sysUserService.add(bean);
		} else {
			if (count > 1) {
				throw new ServiceException("用户已存在.");
			}
			sysUserService.updateBySelective(bean);
		}
		sendSuccessMessage(response, "保存成功~");
	}

	@RequestMapping("/getId.do")
	public void getId(Integer sid, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = getRootMap();
		SysUser bean = sysUserService.queryById(sid);
		if (bean == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", bean);
		HtmlUtil.writerJson(response, context);
	}

	@RequestMapping("/delete.do")
	public void delete(Integer[] sid, HttpServletResponse response)
			throws Exception {
		sysUserService.delete(sid);
		sendSuccessMessage(response, "删除成功");
	}

	/**
	 * 添加或修改数据
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updatePwd.do")
	public void updatePwd(Integer sid, String oldPwd, String newPwd,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		boolean isAdmin = SessionUtils.isAdmin(request); // 是否超级管理员
		SysUser bean = sysUserService.queryById(sid);
		if (bean.getSid() == null || DELETED.YES.key == bean.getDeleted()) {
			sendFailureMessage(response, "该用户不存在或不可用");
			return;
		}
		if (StringUtils.isBlank(newPwd)) {
			sendFailureMessage(response, "请输入新密码");
			return;
		}
		// 不是超级管理员，匹配旧密码
		if (!isAdmin && !MethodUtil.ecompareMD5(oldPwd, bean.getPwd())) {
			sendFailureMessage(response, "原密码错误");
			return;
		}
		bean.setPwd(MethodUtil.MD5(newPwd));
		sysUserService.updateBySelective(bean);
		sendSuccessMessage(response, "保存成功~");
	}

	/**
	 * 用户授权页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/userRole.do")
	public ModelAndView userRole(HttpServletRequest request) throws Exception {
		Map<String, Object> context = getRootMap();
		return forword(MainViewConstant.MAIN_USER_ROLE_VIEW, context);
	}

	/**
	 * 用户授权列表
	 * 
	 * @param model
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/userList.do")
	public void userList(SysUserModel model, HttpServletResponse response)
			throws Exception {
		model.setState(STATE.ENABLE.key);
		dataList(model, response);
	}

	/**
	 * 查询用户信息
	 * 
	 * @param id
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getUser.do")
	public void getUser(Integer sid, HttpServletResponse response)
			throws Exception {
		Map<String, Object> context = getRootMap();
		SysUser bean = sysUserService.queryById(sid);
		if (bean == null) {
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		Integer[] roleIds = null;
		List<SysRoleRel> roles = sysUserService.getUserRole(bean.getSid());
		if (roles != null) {
			roleIds = new Integer[roles.size()];
			int i = 0;
			for (SysRoleRel rel : roles) {
				roleIds[i] = rel.getRoleId();
				i++;
			}
		}

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("sid", bean.getSid());
		data.put("email", bean.getEmail());
		data.put("roleIds", roleIds);
		context.put(SUCCESS, true);
		context.put("data", data);
		HtmlUtil.writerJson(response, context);

	}

	/**
	 * 添加或修改数据
	 * 
	 * @param url
	 * @param classifyId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/addUserRole.do")
	public void addUserRole(Integer sid, Integer roleIds[],
			HttpServletResponse response) throws Exception {
		sysUserService.addUserRole(sid, roleIds);
		sendSuccessMessage(response, "保存成功");
	}
}
